package com.ktjy.ktmall.dao.impl;

import com.ktjy.ktmall.dao.BaseDao;
import com.ktjy.ktmall.dao.OrderDao;
import com.ktjy.ktmall.entity.Order;
import com.ktjy.ktmall.entity.OrderDetail;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @version v1.0
 * @Author 郴州科泰
 * @Create 2024-08-07 - 19:28
 */
public class OrderDaoImpl extends BaseDao implements OrderDao {
    /**
     * 下单
     * @param order 订单对象
     * @return 返回新增成功后的主键值
     */
    @Override
    public int saveOrder(Order order) {
        int orderId = 0;
        conn = this.getConnection();
        String sql = "insert into t_order(`user_id`,`address_id`,`order_price`,`actual_price`,`order_sn`) values(?,?,?,?,?)";
        try {
            pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            pstmt.setInt(1, order.getUserId());
            pstmt.setInt(2, order.getAddressId());
            pstmt.setBigDecimal(3, order.getOrderPrice());
            pstmt.setBigDecimal(4, order.getActualPrice());
            pstmt.setString(5, order.getOrderSn());
            pstmt.executeUpdate();

            rs = pstmt.getGeneratedKeys(); // 得到新增成功的主键值
            if (rs.next()) {
                orderId = rs.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            super.closeAll(rs, pstmt, conn);
        }

        return orderId;
    }

    // 新增订单详情
    @Override
    public int saveOrderDetail(OrderDetail detail) {
        String sql = "insert into t_order_detail(`order_id`,`sku_id`,`goods_id`,`attrsText`,`quantity`) values(?,?,?,?,?)";
        return super.executeUpdate(sql, detail.getOrderId(),detail.getSkuId(),detail.getGoodsId(), detail.getAttrsText(),detail.getQuantity());
    }

    /**
     * 通过订单id查询详情详情
     * @param id 订单id
     * @return 返回订单详情信息
     */
    @Override
    public Order findById(int id) {
        Order order = null;
        String sql = "select * from t_order where id = ?";
        rs = super.executeQuery(sql, id);
        try {
            while (rs.next()) {
                order = new Order(rs.getInt("id"), rs.getString("order_sn"), rs.getInt("user_id"),rs.getInt("address_id"), rs.getInt("order_state"), rs.getBigDecimal("order_price"),rs.getBigDecimal("actual_price"), rs.getString("create_time"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            super.closeAll(rs, pstmt, conn);
        }
        return order;
    }

    /**
     * 通过订单id到t_order_detail表中查询此详情的详情信息。
     * @param orderId 订单id
     */
    @Override
    public List<OrderDetail> findByOrderId(int orderId) {
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Connection conn = this.getConnection();
        List<OrderDetail> list = new ArrayList<>();
        String sql = "select * from t_order_detail where order_id = ?";
        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setObject(1, orderId);
            rs = pstmt.executeQuery();
            while (!rs.isClosed() && rs.next()) {
                OrderDetail od =  new OrderDetail(rs.getInt("id"),rs.getInt("order_id"),rs.getInt("sku_id"),rs.getInt("goods_id"), rs.getString("attrsText"), rs.getInt("quantity"));
                list.add(od);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            super.closeAll(rs, pstmt, conn);
        }
        return list;
    }

    /**
     * 根据订单状态查询订单总数
     * @param orderState 订单状态
     */
    @Override
    public int getCount(int userId, int orderState) {
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Connection conn = this.getConnection();
        int count = 0 ;
        String sql = "select count(*) from t_order where `user_id`=?";
        if (orderState != 0) {
            sql += " AND `order_state` =" + orderState;
        }
        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setObject(1, userId);
            rs = pstmt.executeQuery();
            if (!rs.isClosed() && rs.next()) {
                count = rs.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            super.closeAll(rs, pstmt, conn);
        }
        return count;
    }

    /**
     * 按订单状态分页查询订单列表数据
     * @param from 起始位置偏移量
     * @param pageSize 每页显示的数据行数
     * @param orderState 订单状态
     */
    @Override
    public List<Order> getOrderListPage(Integer from, Integer pageSize, int userId, int orderState) {
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Connection conn = this.getConnection();
        List<Order> list = new ArrayList<>();
        String sql = "select * from t_order where `user_id` = ?";
        if (orderState != 0) {
            sql += " AND `order_state` =" + orderState;
        }
        sql += " order by create_time DESC limit ?,?";
        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setObject(1, userId);
            pstmt.setObject(2, from);
            pstmt.setObject(3, pageSize);
            rs = pstmt.executeQuery();
            while (!rs.isClosed() && rs.next()) {
                Order order = new Order(rs.getInt("id"), rs.getString("order_sn"), rs.getInt("user_id"),rs.getInt("address_id"), rs.getInt("order_state"), rs.getBigDecimal("order_price"),rs.getBigDecimal("actual_price"), rs.getString("create_time"));

                list.add(order);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            super.closeAll(rs, pstmt, conn);
        }
        return list;
    }

    // 更新订单状态
    @Override
    public int updatePayStatus(Order orderInfo) {
        String sql = "update t_order set order_state = ? where id = ? ";
        return super.executeUpdate(sql, orderInfo.getOrderState(), orderInfo.getId());
    }
}
